import React, {useEffect, useState} from 'react';
import {SET_RELEASE_FILTER_CHECKED} from "../../../redux/constants/releases";
import FilterCheckbox from "./FilterCheckbox";

const FilterItem = props => {
  const {typeFilter, filterData, userFilterData, setChecked, maxValue = 5, title = ''} = props;
  let areMore = 0
  const itemHeight = 30;
  const checkboxSmall = [];
  const checkboxBig = [];
  const meta = filterData ? filterData.meta.pagination : ''
  const dataLength = filterData ? filterData.data.length : 0
  if (meta) areMore = meta.total - maxValue

  const [settings, setSettings] = useState({
    hidden: true,
    buttonText: 'Показать еще',
    height: props.maxValue ? props.maxValue * itemHeight : 150
  })

  useEffect(() => {
    if(props.showMore) props.showMore(props.maxValue || 5, props.typeFilter)
  }, [])

  const handleClick = (count, type) => {
    setSettings({...settings,hidden: !settings.hidden, buttonText: !settings.hidden ? 'Показать еще' : 'Скрыть',})
    if(settings.hidden && settings.height < 235) {
      setSettings({...settings,height: 235})
    } else if(settings.height === 235) {
      setSettings({...settings,height: props.maxValue ? props.maxValue * 30 : 150})
    }
    if(props.filterData.data.length !== count && settings.hidden) props.showMore(count, type)
  }

  filterData && filterData.data.forEach((item, index) => {
    if (index < maxValue) {
      checkboxSmall.push(
        <FilterCheckbox
          typeFilter={typeFilter}
          key={item.id}
          data={item}
          userFilterData={userFilterData}
          setChecked={setChecked}
          typeCheck={SET_RELEASE_FILTER_CHECKED}
        />
      )
    } else {
      checkboxBig.push(
        <FilterCheckbox
          typeFilter={typeFilter}
          key={item.id}
          data={item}
          userFilterData={userFilterData}
          setChecked={setChecked}
          typeCheck={SET_RELEASE_FILTER_CHECKED}
        />
      )
    }
  })

  return (
    <React.Fragment>
      <div className="multi-range-title pb-75">
        <h6 className="filter-title mb-0">{title}</h6>
      </div>
      <div className={`check-release-filter ${areMore ? 'release-filter__scroller-container' : 'filter-item-container'}`}>
        <div
          className={`release-filter__items ${areMore > 0 ? 'release-filter__scroller' : ''}`}
          style={{
            height: `${dataLength < maxValue ? dataLength * itemHeight : settings.height}px`
          }}
        >
          <div>{checkboxSmall}</div>
          <div hidden={settings.hidden}>{checkboxBig}</div>
        </div>
        {
          areMore > 0 ?
            <span onClick={() => handleClick(meta.total, typeFilter)} className="release-filter__item-button">
              {settings.buttonText} {settings.hidden && areMore > 0 ? areMore : ''}
          </span> : ''
        }
      </div>
      <hr/>
    </React.Fragment>
  )
}

export default FilterItem;
